package thread;

public class SyncDemo {
    public static void main(String[] args) {

        Table table = new Table();
        Thread t1 = new Thread(){
            @Override
            public void run() {

                while (true){
                    int bean = table.getBean();
                    Thread.yield();
                    if (bean<=0){
                        break;
                    }
                    System.out.println(getName()+":"+bean);
                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {

                while (true){
                    int bean = table.getBean();
                    Thread.yield();
                    if (bean<=0){
                        break;
                    }
                    System.out.println(getName()+":"+bean);
                }
            }
        };

        t1.start();
        t2.start();
    }
}
class Table{
    private Integer beans=20;

    public synchronized Integer getBean() {
        if (beans==0){
            System.out.println("没有豆子了");
        }
        Thread.yield();
        return beans--;
    }
}
